import React, { Component } from 'react';
import axios from 'axios';
import { Form, Icon, Input, Button, Checkbox, message } from 'antd';
import './index.less';
import store from '../../redux/index';
const FormItem = Form.Item;

class LoginForm extends React.Component {
    handleSubmit = (e) => {
      e.preventDefault();
      this.props.form.validateFields((err, values) => {
        if (!err) {
          axios.post('/api/auth/jwt/token', values)
            .then(function (response) {
              if (response.data.token !== '') {
                var userData = JSON.parse(response.config.data);
                sessionStorage.setItem('token', response.data.token);
                sessionStorage.setItem('username', userData.username);
                store.dispatch({ type: 'login' });
                window.location.href = '';
              } else {
                message.error('用户名或密码错误');
              }
            })
            .catch(function (error) {
              message.error('服务不可用，请稍后重试');
            });
        } else {
          console.log('Received values of form: ', values);
        }
      });

    }


    render() {
      const { getFieldDecorator } = this.props.form;
      return (
        <div className="login">
          <Form onSubmit={this.handleSubmit} className="login-form">
            <p>BaaS-admin</p>
            <FormItem>
              {getFieldDecorator('username', {
                rules: [{ required: true, message: '请输入用户名!' }],
              })(
                <Input size="large" prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="用户名" />
              )}
            </FormItem>
            <FormItem>
              {getFieldDecorator('password', {
                rules: [{ required: true, message: '请输入密码!' }],
              })(
                <Input size="large" prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="密码" />
              )}
            </FormItem>
            <FormItem>
              <Button size="large" type="primary" htmlType="submit" className="login-form-button">
                    登录
              </Button>
            </FormItem>
          </Form>
        </div>
      );
    }
}



const Login = Form.create()(LoginForm);
export default Login;
